package com.lxj;


import javax.media.jai.JAI;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.ColorModel;
import java.io.IOException;

public class ImageData {
    public void getImagePixel(BufferedImage bi, String path) throws Exception {
        int[] rgb = new int[3];
        //很重要的方法---将图片的RGB色域空间转化为CMYK色域空间
        BufferedImage cmykImg = changeColorSpace(bi);
        int width = bi.getWidth();
        int height = bi.getHeight();
        int minx = bi.getMinX();
        int miny = bi.getMinY();
        for (int i = minx; i < width; i++) {
            for (int j = miny; j < height; j++) {
                int pixel = bi.getRGB(i, j); // 下面三行代码将一个数字转换为RGB数字
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                float[] abc = {rgb[0], rgb[1], rgb[2]};//获取RGB色域空间数组
                bi.setRGB(123, 123, 123);
                //将此像素RGB色值转化为cmyk色值
                float[] cmykRes = cmykImg.getColorModel().getColorSpace().fromRGB(abc);
                //把cmyk色值添加到色域空间
                cmykImg.getColorModel().getColorSpace().toRGB(cmykRes);
            }
        }
        //生成这个cmyk tiff 文件
        JAI.create("filestore", cmykImg, path, "TIFF");
    }

    private BufferedImage changeColorSpace(BufferedImage targetImage) throws IOException {
        final ICC_Profile ip = ICC_Profile.getInstance("CMYK.pf");

        //转化色值空间
        final ColorConvertOp cco = new ColorConvertOp(targetImage.getColorModel().getColorSpace(), new ICC_ColorSpace(ip), null);
        BufferedImage cmykImage = cco.filter(targetImage, null);
        ColorModel c = cmykImage.getColorModel();
        int ty = cmykImage.getColorModel().getColorSpace().getType();
        return cmykImage;
    }

}
